package org.noworks.game;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TiledMap;
import org.noworks.game.engine.Entity;

public class Gameplay extends BasicGameState {
	
	int stateID = -1;
	
	public static boolean[][] collisionMap;
	public static int tileSize;
	
	TiledMap map;
	int mapx = 0;
	int mapy = 0;
	
	Entity player;
	
	Image sandwich;
	float sx;
	float sy;
	float dsx = 1;
	boolean sandwichMoving;
	
	public Gameplay(int stateID) {
		this.stateID = stateID;
	}

	@Override
	public void init(GameContainer gc, StateBasedGame sbg)
			throws SlickException {
		// TODO Auto-generated method stub
		map = new TiledMap("data/maps/map" + Main.world + "-" + Main.level + ".tmx");
		player = new Entity("NYANDROID");
			player.addComponent(new ImageRender("data/img/sprites/Ice Cream Nyandroid.png", "NYANDROID_IMG", 2));
			player.addComponent(new SideScrollerMovement("NYANDROID_MOV"));
		sandwich = new Image("data/img/sprites/Ice Cream Sandwich.png");
		sandwich.rotate(90);
		buildCollisionMap();
		tileSize = (int) (map.getTileHeight() );
	}

	@Override
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
			throws SlickException {
		// TODO Auto-generated method stub
		map.render(mapx, mapy);
		player.render(gc, sbg, g);
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta)
			throws SlickException {
		// TODO Auto-generated method stub
		player.update(gc, sbg, delta);
	}

	@Override
	public int getID() {
		return stateID;
	}
	
	private void buildCollisionMap() {
		collisionMap = new boolean[map.getWidth()][map.getHeight()];
		for (int idx = 0; idx < map.getWidth(); idx++) {
			for (int jdx = 0; jdx < map.getHeight(); jdx++) {
				for (int kdx = 0; kdx < map.getLayerCount(); kdx++) {
					int id = map.getTileId(idx, jdx, 0);
					String value = map.getTileProperty(id, "blocked", "false");
					if ("true".equalsIgnoreCase(value))
						collisionMap[idx][jdx] = true;
					else if (collisionMap[idx][jdx] != true)
						collisionMap[idx][jdx] = false;
				}
			}
		}
	}

}
